<?php

namespace lxs\auth;

use AllowDynamicProperties;
use Exception;

#[AllowDynamicProperties] class AesSecret extends Author
{
    public function __construct($key, $iv)
    {
        $this->secret_key = $key;
        $this->method = 'AES-256-CBC';
        $this->options = OPENSSL_RAW_DATA;
        $this->iv_length = openssl_cipher_iv_length($this->method);
        $this->iv = $iv; // openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->method))
    }


    /**
     * 加密
     * @param $data array 加密数据
     * @return array|string
     */
    public function encrypt(array $data): array|string
    {
        $data = json_encode($data);
        $result = openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
        return [
            'iv' => base64_encode($this->iv),
            'data' => base64_encode($result)
        ];
    }


    /**
     * 解密
     * @param $data string 解密数据
     * @return string
     * @throws Exception
     */
    public function decrypt(string $data): string
    {
        $data = base64_decode($data);
        $iv = base64_decode($this->iv);
        if (strlen($iv) != $this->iv_length) {
            throw new Exception('iv长度不正确');
        }
        return openssl_decrypt($data, $this->method, $this->secret_key, $this->options, $iv);
    }
}
